<template>
  <div class="box">
    <div class="text"><h3>名画浏览登录</h3></div>
    <div>
      <!-- vant 样式 -->
      <!-- 用户名：密码：填写框 -->
      <van-field v-model.trim="username" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]"/>
      <van-field v-model.trim="password" type="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
      <!-- 登录与注册按钮 -->
      <!-- 登录：与数据库进行验证，登录成功跳到User组件 -->
      <!-- 注册：跳到Register页面 -->
      <div style="margin: 16px;">
        <van-row justify="space-between">
          <van-col span="6"><van-button round  type="primary" @click="userLogin(this.username,this.password)">登录</van-button></van-col>
          <van-col span="6"><van-button round  type="primary" @click="userRegister()">注册</van-button></van-col>
        </van-row>
      </div>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      username: '',
      password: '',
      isup: false
    }
  },
  methods: {
    // 映射 mutations 中的方法
    ...mapMutations(['updateTokenInfo']),
    // 用户登录
    async userLogin (username, password) {
      const { data: res } = await this.$http({
        url: '/api/login',
        method: 'POST',
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: qs.stringify({ username: username, password: password })
      })
      // 登录成功跳转到User页面
      if (res.status === 0) {
        // 把登录成功的结果，存储到 vuex 中
        this.updateTokenInfo(res.token)
        // console.info(res)
        this.username = username
        this.$router.push({
          name: 'user',
          params: {
            isup: true,
            username: this.username
          }
        })
        this.$toast('登录成功')
      }
    },
    // 点击注册调转到注册页面
    userRegister () {
      this.$router.push('/register')
    }
  }
}

</script>

<style lang="less" scoped>
.box{
    width: 80%;
    margin: auto;
    margin-top: 20%;
    .text{
      width: 100%;
      margin: auto;
    }
  }
@media screen and (min-width: 1280px) {
  .box{
    width: 40%;
    margin: auto;
    margin-top: 20%;
    border: 2px solid red;
  border-radius: 5px;
    .text{
      width: 100%;
      margin: auto;
      margin-top: 10px;
      margin-bottom: 10px;
    }
  }
}

</style>
